package com.googlecode.cswish.struts.spring.generator;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.googlecode.cswish.struts.spring.ObjectFactory;
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
import com.opensymphony.xwork2.inject.Inject;

/**
 * Convert object type for auto-generation class
 * 
 * @author Jerry.Feng 2008-10-17
 */
@Service
public class GeneratorHelper {
	
	private static final Log log = LogFactory.getLog(GeneratorHelper.class);
	
	@Inject
	private static XWorkConverter xworkConverter;
	
	private static ObjectFactory objectFactory;
	
	@Inject
	public void setXWorkConverter(XWorkConverter xworkConverter) {
		GeneratorHelper.xworkConverter = xworkConverter;
	}
	
	@Resource
	public void setObjectFactory(ObjectFactory objectFactory) {
		GeneratorHelper.objectFactory = objectFactory;
	}
	
	public static <T> T convert(Object value, Class<T> toType) {
		if (value != null && toType.isAssignableFrom(value.getClass())) {
			return (T)value;
		}
		
		try {
			T newValue = (T) xworkConverter.convertValue(null, null, null, null, value, toType);
			return newValue;
		} catch (Exception ex) {
		}
		return null;
	}
	
	public static Object create(Class<?> type) {
		Object obj = objectFactory.getBean(type, false);
		if (obj == null) {
			log.error("Can't find the service object:" + type.getName());
		}
		return obj;
	}
}